package org.oimwrapper.connectors.common;

import Thor.API.Operations.*;
import java.io.*;
import java.util.*;

import org.oimwrapper.connectors.*;
import org.oimwrapper.connectors.exceptions.*;

/**
 * Imports multiple XML files into OIM in one, serial operation.<p>
 *
 * This task expects the following parameters, in addition to the standard
 * parameters in the {@link OIMTaskBase} class.
 * <ul>
 * <li><code>File</code> The name/path of a single XML file to import into OIM.</li>
 * <li><code>Directory</code> The path to a directory on the OIM server which contains
 *                            xml files to import.  All <i>.xml</i> files in that directory
 *                            will be processed.</li>
 * <li><code>Proceed</code> Set this to <code>true</code> to actually proceed with the import,
 *                          <code>false</code> (the default setting) if the task should only 
 *                          parse the XML files to check for validity.</li>
 * </ul>
 */
public class OIMBulkImporter extends OIMTaskBase {

	/**
	 * True if a stop has been requested for this task.
	 */
	private boolean stop;
    
	/**
	 * Default constructor.
	 */
	public OIMBulkImporter() {
		super("OIMWRAPPER.TASK");
		stop = false;
	}

	/**
	 * This method is called by the scheduler to execute the task instance.
	 */
	public void execute() {
		try {
			String directory = getAttribute("Directory");
			String file = getAttribute("File");
			if (directory != null) {
				File[] files = (new File(directory)).listFiles();
				for (int i = 0; !stop && i < files.length; i++) {
					if (files[i].isFile()) {
						processFile(files[i]);
					}
				}
			} else if (file != null) {
				processFile(new File(file));
			} else {
				throw new OIMMissingAttributeException("File");
			}
		} catch (Exception e) {
			OIMExceptionHandler.handleException(logger, e, getClass());
		}
	}

	/**
	 * This method is called by the scheduler to stop a running task instance.
	 * 
	 * @return <code>true</code>
	 */
	public boolean stop() {
		logger.warn(" ---- Stopping current task ---- ");
		stop = true;
		return stop;
	}
	
	/**
	 * Imports a single file into OIM.
	 * 
	 * @param ImportData The file to import.
	 * @exception Exception
	 */
	protected void processFile(File ImportData) throws Exception {
		logger.warn("Processing: " + ImportData.getName());
		try {
			tcImportOperationsIntf importOp = (tcImportOperationsIntf) getUtility(tcImportOperationsIntf.class);
			if (!importOp.isLockAcquired()) {
				importOp.acquireLock(true);
			}
			BufferedReader reader = new BufferedReader(new FileReader(ImportData));
			String xml = "";
			while (reader.ready()) {
				xml += reader.readLine();
			}
			reader.close();
			Collection data = importOp.addXMLFile(ImportData.getName(), xml);
			if (getBooleanAttribute("Proceed", false)) {
				importOp.performImport(data);
				logger.warn("Imported " + ImportData.getName() + " succcessfully.");
			}
		} catch (Exception e) {
			OIMExceptionHandler.handleException(logger, e, getClass());
		}
	}
}